/**
 * async 其实是对generator的封装
 * 1. 自动执行generator  thrunk函数或者Promise.then()
 * 2. 返回值是Promise generator是生成器对象
 * 3. await 返回值是Promise.resolve/reject
 * 4. 异常处理
 */

/**
 *  babel代码
 * @param {*} fn 
 * @returns 
 */
function _asyncToGenerator(fn) {
    // return一个function，和async保持一致。我们的run直接执行了Generator，其实是不太规范的
    return function () {
        var self = this
        var args = arguments
        return new Promise(function (resolve, reject) {
            var gen = fn.apply(self, args);

            //相当于我们的_next()
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);
            }
            //处理异常
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);
            }
            _next(undefined);
        });
    };
}

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
